package GUI;

import javax.swing.table.AbstractTableModel;

import lejos.pc.comm.NXTConnectionState;
import lejos.pc.comm.NXTInfo;

/**
 * A custom table model class extending the AbstractTableModel abstract class.
 * Represents a table of NXTInfos for use as the data model in a table view.
 * @author Danny Johansen, Didzis Petkus, Liviu Berheci.
 *
 */
public class NXTTableModel extends AbstractTableModel {

	private static final long serialVersionUID = 6504996414986501768L;
	// private final String[] columnNames = { "Name", "Address",
	// "Connection State" };
	private final String[] columnNames = { "Name", "Connection State" };
	private final int INDEX_NAME = 0;
	// private final int INDEX_ADDRESS = 1;
	private final int INDEX_STATE = 1;

	// private ArrayList<NXTInfo> _nxts;
	private Object[][] data;

	/**
	 * Constructor with a NXTInfo array.
	 * @param nxts - NXTInfo array to fill the table.
	 */
	public NXTTableModel(NXTInfo[] nxts) {
		update(nxts);
	}

	/**
	 * Updates the entire model with a new NXTInfo array collection.
	 * <br><br>Creates an empty table if null is passed.
	 * @param nxts - NXTInfo array or <b>null</b> to fill the table.
	 */
	public void update(NXTInfo[] nxts) {

		int numNxts = nxts != null ? nxts.length : 0;

		// if (numNxts > 0) {
		// _nxts = new ArrayList<>();
		// for (int i = 0; i < nxts.length; i++) {
		// _nxts.add(nxts[i]);
		// }
		// }

		// System.out.println("Data Length: " + data.length);

		// System.out.println("Data is 0");

		data = new Object[numNxts][columnNames.length];

		for (int i = 0; i < numNxts; i++) {
			data[i][INDEX_NAME] = nxts[i].name;
			// data[i][INDEX_ADDRESS] = nxts[i].deviceAddress;
			data[i][INDEX_STATE] = nxts[i].connectionState == NXTConnectionState.LCP_CONNECTED ? "Connected"
					: "Disconnected";
		}

		fireTableDataChanged();
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return data.length;
		// return nxts != null ? nxts.length : 0;
	}

	@Override
	public Object getValueAt(int row, int col) {
		return data[row][col];
	}

	@Override
	public String getColumnName(int col) {
		return columnNames[col];
	}

	// public NXTInfo getInfo(int selection) {
	// return nxts[selection];
	// }
}
